﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace library
{
    partial class Peer
    {
        internal byte[] Address = new byte[Parameters.addressSize];

        internal IPEndPoint EndPoint;

        public override string ToString()
        {
            return string.Concat(
                string.Join(".", Address),
                ":\t",
                string.Join(".", EndPoint.Address.GetAddressBytes()),
                ":\t",
                EndPoint.Port);
        }

        internal IEnumerable<byte> ToBytes()
        {
            return Address.Concat(
                    Addresses.ToBytes(EndPoint)).ToArray();
        }

        internal Peer(IPEndPoint iPEndPoint, byte[] address = null)
        {
            Address = address ?? Address;

            EndPoint = iPEndPoint;
        }

        internal static Peer FromBytes(byte[] data)
        {
            return new Peer(
                new IPEndPoint(
                    new IPAddress(data.Skip(Parameters.addressSize).Take(Parameters.ipv4Addresssize).ToArray()),
                        BitConverter.ToUInt16(data, Parameters.addressSize + Parameters.ipv4Addresssize)),
                data.Take(Parameters.addressSize).ToArray());
        }

        internal static Peer CreateLocalPeer()
        {
            return new Peer(
                new IPEndPoint(IPAddress.Any, Client.P2pPort),
                Client.P2pAddress);
        }
    }
}
